﻿(function ($) {
	var $colledge = $('#colledge') // 学院控件
		,$course = $('#course') // 专业
		,$unit = $('#unit')   // 班级
		,$teacher = $('#teacher') // 教师
	var unitUrl = '/unit/unitof/'; // 级联路径
	
	// 事件注册功能
	var regEvent = function () {
		$unit.click(function (e) {
			$('#element').toggle('fast');
			stopBubble(e);
		});

		$(document).click(function (e) {
			$('#element').hide('fast');
			stopBubble(e);
		});

		$('#element').click(function (e) {
			stopBubble(e);
		});
	};
 
	// 返回功能
	$('#back').click(function () {
		window.history.go(-1);
	});

	// 保存
	var save = function () {
		$('#my_form').postFormData().customSubmit(function () {
			var postData = $('#my_form').serialize()
				,resultData = getPostData(postData);
			resultData.unit = $unit.attr('data-value');
			$.post(keter.reqRoot + '/add', resultData, function (data) {
				if(data.message === 'SUCCESS'){
					alert('添加成功。');
					//window.location.href=keter.context;
				}
			});
		});
	};

	var getTreeInfo = function () {
		$.get(keter.context + unitUrl + '1', function (data) {
			var setting = {
				async: {
					enable: true,
					url : keter.context + unitUrl,
					autoParam:["id"]
				}
				,callback : {
					onClick : treeNodeClick
					, onAsyncSuccess : function () {
						passHeight();
					}
				}
			};
			$.fn.zTree.init($("#appTree"), setting, data);
		});
	};

	// 节点点击事件
	function treeNodeClick (e, treeId, treeNode, clickFlag) {
		stopBubble(e);
		var level = treeNode.level,
			parentNode = treeNode.getParentNode();
//		if (level === 2) { // level2为专业
			$unit.val(treeNode.Name).attr('data-value', treeNode.id);
			//console.log(treeNode);
			alert($unit.val());
			//getTeachers(parentNode.id);
			$('#element').hide('fast');
//		}
	}
	
$.fn.getFormData = function (options) {
		var $data = options,
			$form = $(this),
			url = $form.attr('action');
		
	var defaultSubmit = function () {
		$form.submit(function (e) {
			stopDefault(e)
			form = $(this);
			var postData = getPostData(form.serialize());	
			$.post(url, postData, function(data){
				var result;
				if (data && data.responseJSON) {
					result = data.responseJSON.message;
				} else {
					result = data.message;
				}
				// 调整页面
				if (result === 'SUCCESS') {
					alert('添加成功！');
					window.location.href = keter.path + '/login';
				} else {
					alert(result);
				}
			});
		});	
	};
	return {
		defaultSubmit : defaultSubmit
	}
};
	
	var main = function () {
		getTreeInfo();
		regEvent();
//		save();
	};

	return main();
})(jQuery);   
